package com.adtech.farmProducts.activities.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Build;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.adtech.common.Common;
import com.adtech.common.http.AsyncHttpPostFormData;
import com.adtech.common.http.AsyncHttpResponse;
import com.adtech.common.http.AsyncOkHttpClient;
import com.adtech.common.http.AsyncResponseHandler;
import com.adtech.common.model.RspModel;
import com.adtech.common.utils.AccountManagers;
import com.adtech.common.utils.FileUtils;
import com.adtech.common.utils.TimeUtil;
import com.adtech.common.widgets.dialog.CustomDialog;
import com.adtech.common.widgets.recycler.RecyclerViewAdapter;
import com.adtech.common.widgets.recycler.decoration.DividerItemDecoration;
import com.adtech.farmProducts.App;
import com.adtech.farmProducts.R;
import com.adtech.farmProducts.adapter.ExtraPriceListAdapter;
import com.adtech.farmProducts.base.BaseNfcActivity;
import com.adtech.farmProducts.blue.adapter.Event;
import com.adtech.farmProducts.interfaces.IBluetoothGattCallback;
import com.adtech.farmProducts.model.CommodityInfo;
import com.adtech.farmProducts.model.DefaultCommodity;
import com.adtech.farmProducts.model.FUserInfo;
import com.adtech.farmProducts.model.NFCResult;
import com.adtech.farmProducts.utils.Constants;
import com.adtech.farmProducts.widget.ClearTextIconEditText;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yalantis.ucrop.UCrop;

import java.io.IOException;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Time:2020/6/20
 * Created by xiaocz
 * Describe 装箱入库
 */
public class InsertActivity extends BaseNfcActivity implements EasyPermissions.PermissionCallbacks {

    @BindView(R.id.edit_code)
    TextView edit_code;
    @BindView(R.id.edit_name)
    TextView edit_name;
    @BindView(R.id.ck_default)
    CheckBox checkBox;
    @BindView(R.id.edit_gs_name)
    TextView edit_gs_name;
    @BindView(R.id.tv_address)
    TextView tv_address;
    @BindView(R.id.tv_time)
    TextView tv_time;
    @BindView(R.id.btn_right)
    TextView btn_right;
    @BindView(R.id.layout_camera)
    LinearLayout layout_camera;
    @BindView(R.id.edit_weight)
    ClearTextIconEditText edit_weight;


    /**
     * DATA
     */
    private int productId;
    private BluetoothAdapter mBluetoothAdapter;

    public static void show(Context context) {
        Intent intent = new Intent(context, InsertActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutSourceId() {
        return R.layout.activity_insert;
    }


    private BluetoothGatt mBluetoothGatt;

    @Override
    protected void initData() {
        if (Constants.getLocation() != null) {
            String address = Constants.getLocation().getAddress();
            if (address != null) {
                int index = address.indexOf("靠近");
                tv_address.setText(index > 0 ? address.substring(0, index) : address);
            }
        }
        btn_right.setText("电子秤连接");
        FUserInfo info = new Gson().fromJson(AccountManagers.getAccount(), FUserInfo.class);
        edit_gs_name.setText(info.getInfo().getCompanyName());
        tv_unit.setText(cancelReason[0]);
        tv_time.setText(TimeUtil.stamp2Time(System.currentTimeMillis(), Common.DateType.dateIF));
        getDefault();
        super.initData();
        onDialogNFC();
        init();
    }

    @OnClick({R.id.edit_name, R.id.tv_unit, R.id.tv_weight, R.id.btn_right, R.id.layout_camera, R.id.btn_submit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.edit_name:
                Intent intent = new Intent(mContext, CommodityManagementListActivity.class);
                startActivityForResult(intent, 200);
                break;
            case R.id.tv_unit:
                hideKeyboard();
                dialogUnit();
                break;
            case R.id.btn_right://电子秤连接
                mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // null:表示不支持蓝牙
                if (mBluetoothAdapter != null) {
                    boolean enabled = mBluetoothAdapter.isEnabled(); // true:处于打开状态, false:处于关闭状态
                    if (!enabled) {
                        startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), 1);
                        return;
                    }
                    //如果当前在搜索，就先取消搜索
                    if (mBluetoothAdapter.isDiscovering()) {
                        mBluetoothAdapter.cancelDiscovery();
                    }
                    onDialogExtraCharges();
                    mBluetoothAdapter.startDiscovery();//开启搜索
                } else {
                    App.getInstance().showMessage("该设备不支持蓝牙！");
                }

                break;
            case R.id.tv_weight:
                hideKeyboard();
                dialogWeightUnit();
                break;
            case R.id.layout_camera:
                checkAndRequestPermission();
                break;
            case R.id.btn_submit:
                onCheck();
                break;
        }
    }


    private void init() {
        // 设置广播信息过滤
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);//每搜索到一个设备就会发送一个该广播
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//当全部搜索完后发送该广播
        filter.setPriority(Integer.MAX_VALUE);//设置优先级
        // 注册蓝牙搜索广播接收者，接收并处理搜索结果
        this.registerReceiver(receiver, filter);
    }

    List<Event> bluetoothList = new ArrayList<>();

    BroadcastReceiver receiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(BluetoothDevice.ACTION_FOUND)) {
                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getName() != null) {// 防止重复添加
                    boolean isCan = false;
                    for (int i = 0; i < bluetoothList.size(); i++) {
                        if (bluetoothList.get(i).getDevice().getAddress().equals(device.getAddress())) {
                            isCan = true;
                            break;
                        }
                    }
                    if (!isCan) {
                        bluetoothList.add(new Event(device.getName(), device));
                        mAdapter.replace(bluetoothList);
                    }
                }
            } else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_STARTED)) {
                App.getInstance().showMessage("正在扫描");
            } else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
                if (tv_title != null) {
                    tv_title.setText("扫描完成，点击列表中的设备连接");
                }
            }
        }
    };
    private RecyclerView mRecyclerView;
    private TextView tv_title;
    private ExtraPriceListAdapter mAdapter;
    private CustomDialog dialogBlue;

    private void onDialogExtraCharges() {
        bluetoothList.clear();
        CustomDialog.Builder builder = new CustomDialog.Builder(mContext);
        View layout = LayoutInflater.from(mContext).inflate(R.layout.dialog_other_charges, null);
        builder.setContentView(layout);
        builder.setGravity(Gravity.BOTTOM);
        builder.setDialogWidthAndPX(WindowManager.LayoutParams.MATCH_PARENT);
        builder.setDialogHeightAndPX(WindowManager.LayoutParams.WRAP_CONTENT);
        dialogBlue = builder.create();
        mRecyclerView = layout.findViewById(R.id.recycler_view);
        tv_title = layout.findViewById(R.id.tv_title);
        tv_title.setText("正在扫描中");
        initExtraList();
        dialogBlue.show();
    }

    /**
     * 初始化列表
     */
    private void initExtraList() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(mContext,
                DividerItemDecoration.VERTICAL, R.drawable.shape_divider_line, 16, true));
        mAdapter = new ExtraPriceListAdapter(new RecyclerViewAdapter.AdapterListenerImpl<Event>() {
            @Override
            public void onItemClick(RecyclerViewAdapter.ViewHolder<Event> holder, Event data, int position) {
                super.onItemClick(holder, data, position);
                loadingDialogShow(true);
                if (mBluetoothAdapter != null) {
                    mBluetoothAdapter.cancelDiscovery();
                }
                mBluetoothGatt = data.getDevice().connectGatt(mContext, true, mGattCallback, BluetoothDevice.TRANSPORT_LE);
                if (dialogBlue != null) {
                    dialogBlue.dismiss();
                }
            }
        });
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.replace(bluetoothList);
    }

    /**
     * 数据效验
     */
    private void onCheck() {
        String valueCode = String.valueOf(edit_code.getText()).trim();
        String valueName = String.valueOf(edit_name.getText()).trim();
        String valueWeight = String.valueOf(edit_weight.getText()).trim();
        String valueAddress = String.valueOf(tv_address.getText()).trim();
        if (TextUtils.isEmpty(valueCode)) {
            App.getInstance().showMessage("请获取溯源码！");
            return;
        }
        if (TextUtils.isEmpty(valueName)) {
            App.getInstance().showMessage("请输入产品名称！");
            return;
        }
        if (TextUtils.isEmpty(valueWeight)) {
            App.getInstance().showMessage("请输入产品重量！");
            return;
        }
        if (TextUtils.isEmpty(valueAddress)) {
            App.getInstance().showMessage("获取地址中请稍后！");
            if (Constants.getLocation() != null) {
                String address = Constants.getLocation().getAddress();
                if (address != null) {
                    int index = address.indexOf("靠近");
                    tv_address.setText(index > 0 ? address.substring(0, index) : address);
                }
            }
            return;
        }
        onInsert(valueAddress, productId, valueName, valueCode, valueWeight);
    }

    @BindView(R.id.tv_unit)
    TextView tv_unit;
    @BindView(R.id.tv_weight)
    TextView tv_weight;


    /**
     * 获取默认商品
     */
    private void getDefault() {
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        okHttpClient.posts(Common.Constant.API_IP + "product/getDefault", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                Type type = new TypeToken<RspModel<DefaultCommodity>>() {
                }.getType();
                RspModel<DefaultCommodity> rspModel = getAnalysis(response, type, "录入历史");
                if (rspModel == null) {
                    return;
                }
                if (rspModel.getCode() == 1 && rspModel.getData() != null && !"[]".equals(rspModel.getData().toString())) {
                    DefaultCommodity defaultCommodity = rspModel.getData();
                    productId = defaultCommodity.getProductId();
                    edit_name.setText(defaultCommodity.getProductName());
                    tv_unit.setText(defaultCommodity.getPackUnit());
                    tv_weight.setText(defaultCommodity.getUnit());
                    checkBox.setChecked(true);
                }
            }
        });
    }

    /**
     * 设置默认商品
     */
    private void setDefault(String packUnit, int productId, String unit) {
        loadingDialogShow(false);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("packUnit", packUnit);//必填：装单位（袋、箱）
        asyncHttpPostFormData.addFormData("productId", productId);//必填：产品ID
        asyncHttpPostFormData.addFormData("unit", unit);//必填：重量单位（克、千克）
        okHttpClient.posts(Common.Constant.API_IP + "product/setDefault", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                checkBox.setChecked(false);
                onDismiss();
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<String>>() {
                }.getType();
                RspModel<String> rspModel = getAnalysis(response, type, "设置默认商品");
                if (rspModel == null) {
                    checkBox.setChecked(false);
                    return;
                }
                if (rspModel.getCode() == 1 && "success".equals(rspModel.getMessage())) {
                    App.getInstance().showMessage("设置默认商品成功！");
                    checkBox.setChecked(true);
                } else {
                    checkBox.setChecked(false);
                }
            }
        });
    }

    /**
     * 数据录入
     */
    private void onInsert(String address, int productId, String productName, String sourceCode, String weight) {
        loadingDialogShow(false);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("companyId", new Gson().fromJson(AccountManagers.getAccount(), FUserInfo.class).getInfo().getCompanyId());
        asyncHttpPostFormData.addFormData("address", address);//必填：地址
        asyncHttpPostFormData.addFormData("handleTime", tv_time.getText().toString());//必填：操作时间（格式：yyyy-MM-dd HH:mm:ss）
        asyncHttpPostFormData.addFormData("handleType", 1);//必填：经手动作（1、入库，2、开箱验货，3、标签破损）
        asyncHttpPostFormData.addFormData("imageUrl", imageUrl);//图片地址（多张图片用英文逗号隔开）
        asyncHttpPostFormData.addFormData("packUnit", tv_unit.getText().toString());//必填：装单位（袋、箱）
        asyncHttpPostFormData.addFormData("productId", productId);//必填：产品ID：开箱验货封箱时必填，更换标签时必填
        asyncHttpPostFormData.addFormData("productName", productName);//必填：产品名称
        asyncHttpPostFormData.addFormData("sourceCode", sourceCode);//必填：溯源码
        asyncHttpPostFormData.addFormData("unit", tv_weight.getText().toString());//必填：重量单位（克、千克）
        asyncHttpPostFormData.addFormData("userId", AccountManagers.getUserId());//必填：会员ID
        asyncHttpPostFormData.addFormData("weight", weight);//必填：产品单位重量
        okHttpClient.posts(Common.Constant.API_IP + "handle/recordTrace", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                onDismiss();
                App.getInstance().showMessage(getResources().getString(R.string.connection_error));
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<String>>() {
                }.getType();
                RspModel<String> rspModel = getAnalysis(response, type, "数据录入");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 1:
                        imageUrl = "";
                        onDialogNext();
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }

    /**
     * 录入成功-提示
     */
    private void onDialogNext() {
        final Dialog alert = new Dialog(mContext);
        alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
        alert.setContentView(R.layout.dialog_hint);
        alert.findViewById(R.id.btn_exit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                alert.dismiss();
            }
        });
        alert.findViewById(R.id.btn_submit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_time.setText(TimeUtil.stamp2Time(System.currentTimeMillis(), Common.DateType.dateIF));
                edit_code.setText("");
                imageUrl = "";
                edit_weight.setText("");
                alert.dismiss();
            }
        });
        alert.show();
        Window window = alert.getWindow();
        if (window != null) {
            window.setBackgroundDrawableResource(android.R.color.transparent);
            WindowManager.LayoutParams lp = alert.getWindow().getAttributes();
            DisplayMetrics dm = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            lp.width = (int) (dm.widthPixels * 0.88); //设置宽度
            alert.getWindow().setAttributes(lp);
        }
    }

    private String[] cancelReason = {"箱", "袋"};
    private String[] weightUnit = {"克(g)", "千克(kg)"};

    /**
     * 显示-包装单位
     */
    private void dialogUnit() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("选择包装类型");
        builder.setItems(cancelReason, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                tv_unit.setText(cancelReason[which]);
            }
        });
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.show();
    }

    private void dialogWeightUnit() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("选择重量单位");
        builder.setItems(weightUnit, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                tv_weight.setText(weightUnit[which]);
            }
        });
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.show();
    }


    @OnCheckedChanged({R.id.ck_default})
    public void OnCheckedChangeListener(CompoundButton view, boolean isCheck) {
        if (view.isPressed()) {
            switch (view.getId()) {
                case R.id.ck_default:
                    if (isCheck) {
                        if (productId != 0) {
                            setDefault(tv_unit.getText().toString().trim(), productId, tv_weight.getText().toString().trim());
                        } else {
                            App.getInstance().showMessage("请选择商品名称！");
                            checkBox.setChecked(false);
                        }
                    }
                    break;
            }
        }
    }

    /**
     * 标签是否已使用
     */
    private void onCodeCheck(String sourceCode) {
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("sourceCode", sourceCode);
        okHttpClient.posts(Common.Constant.API_IP + "handle/checkPacked", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                Type type = new TypeToken<RspModel<String>>() {
                }.getType();
                RspModel<String> rspModel = getAnalysis(response, type, "标签是否已使用");
                if (rspModel == null) {
                    return;
                }
                if (rspModel.getMessage().contains("已使用")) {
                    App.getInstance().showMessage(rspModel.getMessage());
                    edit_code.setText("");
                }
            }
        });
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 如果裁剪错误则直接返回不做任何操作
        if (resultCode == UCrop.RESULT_ERROR) {
            return;
        }
        // 如果有返回值
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CAMERA_REQUEST_CODE: // 拍照
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        cropRawPhoto(providerUri);
                    } else {
                        cropRawPhoto(mUri);
                    }
                    break;
                case GALLERY_REQUEST_CODE:// 相册选择
                    cropRawPhoto(data.getData());
                    break;
                case CROP_REQUEST_CODE:
                    Uri uri = UCrop.getOutput(data);
                    if (uri != null) {
                        upHeardImage(FileUtils.getFilePathByUri(mContext, uri), layout_camera);
                    } else {
                        App.getInstance().showMessage("获取内容为空！");
                    }
                    break;
                default:
                    break;
            }
        }
        if (resultCode == 200 && requestCode == 200) {
            CommodityInfo commodityInfo = (CommodityInfo) data.getSerializableExtra("CommodityInfo");
            if (commodityInfo != null) {
                productId = commodityInfo.getProductId();
                edit_name.setText(commodityInfo.getProductName());
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        NFCResult result = resolveReadIntent(detectedTag);
        if (result != null) {
            if (result.isState()) {
                edit_code.setText(result.getResult().getUid());
                onCodeCheck(result.getResult().getUid());
                if (dialog != null) {
                    dialog.dismiss();
                }
            } else {
                App.getInstance().showMessage(result.getMessage());
            }
        }
    }

    // BLE回调操作
    private BluetoothGattCallback mGattCallback = new IBluetoothGattCallback() {

        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
            if (newState == BluetoothProfile.STATE_CONNECTED) {// 连接成功
                App.getInstance().showMessage("蓝牙连接成功");
                mBluetoothGatt.discoverServices();
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {// 连接断开
                App.getInstance().showMessage("蓝牙连接断开");
            }
            onDismiss();
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {//发现服务，在蓝牙连接的时候会调用
            List<BluetoothGattService> list = mBluetoothGatt.getServices();
            BluetoothGattCharacteristic alertLevel = null;
            for (BluetoothGattService bluetoothGattService : list) {
                String str = bluetoothGattService.getUuid().toString();
                List<BluetoothGattCharacteristic> gattCharacteristics = bluetoothGattService
                        .getCharacteristics();
                for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
                    Log.e("gattCharacteristic", " ：" + gattCharacteristic.getUuid());
                    if ("49535343-1e4d-4bd9-ba61-23c647249616".equals(gattCharacteristic.getUuid().toString())) {
                        alertLevel = gattCharacteristic;
                    }
                }
            }
            enableNotification(gatt, alertLevel);//必须要有，否则接收不到数据
        }

        private void enableNotification(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            if (gatt == null || characteristic == null)
                return;
            mBluetoothGatt.setCharacteristicNotification(characteristic, true);
            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
                    UUID.fromString(Constants.CLIENT_CHARACTERISTIC_CONFIG));
            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            mBluetoothGatt.writeDescriptor(descriptor);
            mBluetoothGatt.requestMtu(50);
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicChanged(gatt, characteristic);
            StringBuilder sbu = new StringBuilder();
            for (int i = characteristic.getValue().length - 1; i > 0; i--) {
                int v = characteristic.getValue()[i - 1];
                sbu.append((char) v);
            }
            BigDecimal decimal = new BigDecimal(sbu.toString());
            decimal = decimal.setScale(2, BigDecimal.ROUND_UP);
            i++;
            if (edit_weight != null && i == 10) {
                i = 0;
                final BigDecimal finalDecimal = decimal;
                runOnUiThread(new Runnable() {
                    @SuppressLint("SetTextI18n")
                    public void run() {
                        edit_weight.setText(finalDecimal.toString());
                    }
                });
            }
        }

        private int i = 0;
    };

    @Override
    protected void onDestroy() {
        if (mBluetoothAdapter != null) {
            mBluetoothAdapter.cancelDiscovery();
        }
        super.onDestroy();
    }
}
